package ConexaoBackupBD;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.JOptionPane;
 
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class CriptografiaBD {
    
    private static final String METODO_ENCRIPTACAO = "AES";
    public static final byte[] CHAVE = {-81, 92, 27, -9, -45, 67, -7, -108, -119, -74, 72, -80, 48, -79, 95, -11, };
 
    public static String encriptar(byte[] key, String value){ 
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key, METODO_ENCRIPTACAO);
 
            Cipher cipher = Cipher.getInstance(METODO_ENCRIPTACAO);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(value.getBytes());
 
            return new BASE64Encoder().encode(encrypted);
        }
        catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(),
                "Erro ao encriptar informações.",JOptionPane.INFORMATION_MESSAGE);
            return null;
        }
    }
 
    public static String decriptar(byte[] key, String encrypted){
 
        byte[] decrypted = null;
 
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key, METODO_ENCRIPTACAO);
 
            byte[] decoded = new BASE64Decoder().decodeBuffer(encrypted);
 
            Cipher cipher = Cipher.getInstance(METODO_ENCRIPTACAO);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            decrypted = cipher.doFinal(decoded);
        }
        catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(),
                    "Erro ao descriptografar informações.",JOptionPane.INFORMATION_MESSAGE);
        }
 
        return new String(decrypted);
    }
    
//    public static void gerarChave() {
//        try {
//            KeyGenerator keyGen = KeyGenerator.getInstance(METODO_ENCRIPTACAO);
// 
//            System.out.println("Chave AES:");
//            byte[] chave = keyGen.generateKey().getEncoded();
// 
//            System.out.print("{");
//            for (byte b : chave) {
//                System.out.print("" + b + ", ");
//            }
//            System.out.println("}");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
